
<template>
  <div>
    <el-tag
      v-for="tag in dynamicTags"
      :key="tag"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >{{ tag }}</el-tag>
    <el-input
      v-if="inputVisible"
      ref="saveTagInput"
      v-model="inputValue"
      class="input-new-tag"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
  </div>
</template>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
<script>
export default {
  name: 'DynamicTags',
  props: {
    tagArr: {
      type: Array,
      default: () => []
    }
    // ,
    // inputVisible: {
    //   type: Boolean,
    //   default: false
    // },
    // inputValue: {
    //   type: String,
    //   default: ''
    // }
  },
  data() {
    return {
      dynamicTags: this.tagArr,
      inputVisible: false,
      inputValue: ''
    }
  },
  watch: {
    tagArr: {
      immediate: true,
      deep: true,
      handler(newvalue, oldvalue) {
        this.dynamicTags = JSON.parse(JSON.stringify(newvalue))
      }
    }
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      debugger
      if (this.dynamicTags.indexOf(inputValue) >= 0) {
        this.$message({
          message: '已存在该标签',
          type: 'error'
        })
        this.inputVisible = false
        this.inputValue = ''
        return
      }
      if (this.dynamicTags.length >= 5) {
        this.$message({
          message: '最多5个标签',
          type: 'error'
        })
        this.inputVisible = false
        this.inputValue = ''
        return
      }
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>
